package com.loveprogrammer.base.factory;

import com.loveprogrammer.base.bean.ServerConfig;
import com.loveprogrammer.base.network.channel.tcp.str.TcpServerStringInitializer;
import com.loveprogrammer.base.network.channel.websocket.WebSocketChannelInitializer;
import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.exception.ServerException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName ServerChannelFactory
 * @Description channel工厂类
 * @Author admin
 * @Date 2024/2/4 15:13
 * @Version 1.0
 */
public class ServerChannelFactory {
    private static final Logger logger = LoggerFactory.getLogger(ServerChannelFactory.class);

    public static Channel createAcceptorChannel() throws ServerException {
        Integer port = ServerConfig.getInstance().getPort();
        final ServerBootstrap serverBootstrap = ServerBootstrapFactory.createServerBootstrap();
        serverBootstrap.childHandler(getChildHandler());
        logger.info("创建Server...");

        try {
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.awaitUninterruptibly();
            if(channelFuture.isSuccess()) {
                return channelFuture.channel();
            }else{
                String errMsg = "Failed to open socket! Cannot bind to port: " + port + "!";
                logger.error(errMsg);
                throw new ServerException(errMsg);
            }
        } catch (Exception e) {
            logger.debug(port + "is bind");
            throw new ServerException(e);
        }
    }

    private static ChannelInitializer<SocketChannel> getChildHandler() throws ServerException {

        String protocolType = ServerConfig.getInstance().getProtocolType();

        if (ConstantValue.PROTOCOL_TYPE_HTTP.equals(protocolType) || ConstantValue.PROTOCOL_TYPE_HTTPS
                .equals(protocolType)) {
        } else if (ConstantValue.PROTOCOL_TYPE_TCP.equals(protocolType)) {
            return new TcpServerStringInitializer();
        } else if (ConstantValue.PROTOCOL_TYPE_WEBSOCKET.equals(protocolType)) {
            return new WebSocketChannelInitializer();
        } else if (ConstantValue.PROTOCOL_TYPE_PROTOBUF.equals(protocolType)) {
        } else {
        }
        String errMsg = "undefined protocol:" + protocolType + "!";
        throw new ServerException(errMsg);
    }

}
